package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgPlatform;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.pay.UnifiedOrderResult;
import com.ygqh.baby.service.pay.app.weixin.WxAppUtils;
import com.ygqh.baby.service.wechat.WxConfig;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.WebUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 壹家店登录
* @ClassName: YgPlatformLoginController 
* @author (guohao)  
* @date 2018年5月25日 上午11:34:59 
* @version V1.0
 */
@Controller
@RequestMapping("/app/platform")
public class YgPlatformPayController extends BaseController {

	private Logger logger = Logger.getLogger(YgPlatformPayController.class);

	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgFrameCodeService ygFrameCodeService;
	@Autowired
	private YgOrderPaymentService ygOrderPaymentService;
	@Autowired
	private YgWeChatService weChatService;
	@Autowired
	private YgPayService ygPayService;
	@Autowired
	private YgPlatformService ygPlatformService;
	@Autowired
	private YgUserAuthsService ygUserAuthsService;
	@Autowired
	private YgRechargeMemberRecordService ygRechargeMemberRecordService;
	@Autowired
	private YgUserMemberService ygUserMemberService;

	/**
	 * 订单支付
	 * @param orderId
	 * @param appType
	 * @param payType
	 * @param price
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "orderPay")
	@ResponseBody
	public ResponseEntity unifiedOrder(Long orderId, @RequestParam(defaultValue = "Small") AppType appType,
									   @RequestParam(defaultValue = "WeChat") PayType payType, BigDecimal price,
									   HttpServletRequest request) {
		YgUser user = SessionUtil.getCurrentUser();
		String ipAddress = WebUtils.getIpAddr(request).split(",")[0];
		String openId = ygUserAuthsService.getOpenId(user.getId(), PLATFORM_NO, appType);

		YgOrder ygOrder = ygOrderService.findByOrderId(orderId);
		if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
			return ResponseEntity.error("请不要重复付款。", orderId);
		}
		Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());
		YgPlatform platform = ygPlatformService.findByPlatformNo(PLATFORM_NO, appType);
		String paynotifyurl = WxConfig.getWxfwsorderpaynotifyurl();
		UnifiedOrderResult result = ygPayService.unifiedOrder(platform, AppType.Small, PayType.WeChat, paymentCode.toString(), price, ipAddress, openId, paynotifyurl, "");

		ygOrderPaymentService.addPaymentRecord(BusinessModule.Order, orderId.toString(), price, paymentCode.toString(), payType, appType, result.getPrepayId(),
				PLATFORM_NO, result.getPlatformName());
		if(result.getType().equals(Message.Type.error)){
			return ResponseEntity.error(result.getContent());
		}
		return ResponseEntity.success(result);
	}

	private String getOpenId(Long userId, AppType appType, String platformNo) {
		if (AppType.Android.equals(appType) || AppType.Ios.equals(appType)) {
			return null;
		}
		String openId = null;
		if (StringUtils.isBlank(platformNo) || Constant.YIIGOO_PLATFORM_NO.equals(platformNo)) {
			YgUser user = ygUserService.findOpenId(userId);
			if (AppType.WeChat.equals(appType)) {
				openId = user.getOpenId();
			} else if (AppType.Small.equals(appType)) {
				openId = user.getSmallOpenId();
			}
		} else {
			openId = ygUserAuthsService.getOpenId(userId, platformNo, appType);
		}
		return openId;
	}

	/**
	 * 订单支付回调
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "unifiedOrderCallBack")
	public void unifiedOrderCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		ServletInputStream in = request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		String result = new String(out.toByteArray(), "UTF-8");
		ygOrderLogService.addOrderLog(1L, OrderStatus.WaitingSend, "系统",
				"微信支付回调，回调数据 【" + result + "】;");
		String res = weChatService.UnifiedOrderCallBack(result);
		ygOrderLogService.addOrderLog(1L, OrderStatus.WaitingSend, "系统",
				"微信支付回调，返回微信数据 【" + res + "】;");
		logger.debug("\n微信支付回调返回结果：\n" + res);
		out.close();
		in.close();
		response.getWriter().print(res);
	}

	/**
	 * 充值
	 *
	 * @param rechargeType 充值类型
	 * @param appType 支付平台
	 * @param payType 支付类型
	 * @param rechargePrice 支付金额
	 * @param sourceCode 来源source
	 * @param platformNo 平台编号
	 * @param request request
	 * @return
	 */
	@RequestMapping(value = "unifiedRechargeMember")
	@ResponseBody
	public ResponseEntity unifiedRechargeMember(CodeType rechargeType, @RequestParam(defaultValue = "Small") AppType appType,
												@RequestParam(defaultValue = "WeChat") PayType payType,
												@RequestParam BigDecimal rechargePrice, String sourceCode,
												@RequestParam(defaultValue = PLATFORM_NO) String platformNo,
												HttpServletRequest request) {
		YgUser user = SessionUtil.getCurrentUser();
		YgUser userRealInfo = ygUserService.findById(user.getId());
		if (CodeType.RechargeMB.equals(rechargeType) && UserType.Distributor.equals(userRealInfo.getUserType())) {
			return ResponseEntity.error("分销员不能购买女王", null);
		}
		if (CodeType.RechargeAG.equals(rechargeType) && UserType.UserAgent.equals(userRealInfo.getUserType())) {
			return ResponseEntity.error("亲，您已经是壹家店会员，无需购买。", null);
		}
		if (CodeType.RechargeAG.equals(rechargeType) && UserType.Group.equals(userRealInfo.getUserType())) {
			return ResponseEntity.error("亲，您已经是团长，无需购买壹家店会员。", null);
		}
		String openId = getOpenId(user.getId(), appType, platformNo);
		String ipAddress = WebUtils.getIpAddr(request).split(",")[0];
		Long paymentCode;
		if (rechargeType.equals(CodeType.RechargeMB)) {
			rechargePrice = ygUserMemberService.getVipPrice();
			paymentCode = ygFrameCodeService.getFrameCode(rechargeType, new Date());
		} else {
			paymentCode = ygFrameCodeService.getFrameCode(rechargeType, new Date());
		}
		YgPlatform platform = ygPlatformService.findByPlatformNo(platformNo, appType);
		String paynotifyurl = WxAppUtils.wxPayNotifyUrl;

		Map<String, Object> attach = new HashMap<>();
		attach.put("appType", appType);
		attach.put("userId", user.getId());
		attach.put("codeType", rechargeType);

		UnifiedOrderResult result = ygPayService.unifiedOrder(platform, appType, payType,
				paymentCode.toString(), rechargePrice, ipAddress, openId, paynotifyurl, JSON.toJSONString(attach));
		ygRechargeMemberRecordService.addRecord(user.getId(), paymentCode, rechargePrice, "Year", payType,
				appType, sourceCode, rechargeType, platformNo);
		if(result.getType().equals(Message.Type.error)){
			return ResponseEntity.error(result.getContent());
		}
		return ResponseEntity.success(result);
	}
}
